package com.bookstore.view;

import com.bookstore.model.Book;
import com.bookstore.service.BookService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.Vector;

// 书店库存管理系统
//主UI界面
public class BookStoreGUI extends JFrame {
    private BookService bookService;

    private JTable bookTable;
    private DefaultTableModel tableModel;
    private JTextField isbnField, titleField, authorField, priceField, stockField;
    private JButton addButton, updateButton, deleteButton, clearButton, searchButton, lowStockButton, increaseStockButton, sellButton;
    private JTextField searchField, stockIsbnField, stockQuantityField;

    public BookStoreGUI() {
        super("书店库存管理系统");
        bookService = new BookService();
        initComponents();
        loadBooks();
    }

    private void initComponents() {
        // 设置窗口属性
        setSize(1200, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示

        // 主面板，使用 BorderLayout
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 顶部操作面板容器
        JPanel topOperationsPanel = new JPanel();
        topOperationsPanel.setLayout(new BoxLayout(topOperationsPanel, BoxLayout.Y_AXIS));
        
        // 书籍信息管理面板
        JPanel bookInfoPanel = new JPanel(new GridBagLayout());
        bookInfoPanel.setBorder(BorderFactory.createTitledBorder("书籍信息管理"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // 外边距

        // ISBN
        gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST;
        bookInfoPanel.add(new JLabel("ISBN:"), gbc);
        gbc.gridx = 1; gbc.gridy = 0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        isbnField = new JTextField(20);
        bookInfoPanel.add(isbnField, gbc);

        // 书名
        gbc.gridx = 2; gbc.gridy = 0; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
        bookInfoPanel.add(new JLabel("书名:"), gbc);
        gbc.gridx = 3; gbc.gridy = 0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        titleField = new JTextField(20);
        bookInfoPanel.add(titleField, gbc);

        // 作者
        gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
        bookInfoPanel.add(new JLabel("作者:"), gbc);
        gbc.gridx = 1; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        authorField = new JTextField(20);
        bookInfoPanel.add(authorField, gbc);

        // 价格
        gbc.gridx = 2; gbc.gridy = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
        bookInfoPanel.add(new JLabel("价格:"), gbc);
        gbc.gridx = 3; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        priceField = new JTextField(20);
        bookInfoPanel.add(priceField, gbc);

        // 库存
        gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
        bookInfoPanel.add(new JLabel("库存:"), gbc);
        gbc.gridx = 1; gbc.gridy = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        stockField = new JTextField(20);
        bookInfoPanel.add(stockField, gbc);

        // CRUD 按钮
        addButton = new JButton("添加书籍");
        updateButton = new JButton("更新书籍");
        deleteButton = new JButton("删除书籍");
        clearButton = new JButton("清空输入");

        JPanel crudButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        crudButtonPanel.add(addButton);
        crudButtonPanel.add(updateButton);
        crudButtonPanel.add(deleteButton);
        crudButtonPanel.add(clearButton);

        gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 4; gbc.fill = GridBagConstraints.HORIZONTAL;
        bookInfoPanel.add(crudButtonPanel, gbc);
        
        topOperationsPanel.add(bookInfoPanel);
        topOperationsPanel.add(Box.createVerticalStrut(10)); // 添加垂直间距

        // 库存操作面板
        JPanel stockPanel = new JPanel(new GridBagLayout());
        stockPanel.setBorder(BorderFactory.createTitledBorder("库存操作"));
        GridBagConstraints stockGbc = new GridBagConstraints();
        stockGbc.insets = new Insets(5, 5, 5, 5);

        // ISBN
        stockGbc.gridx = 0; stockGbc.gridy = 0; stockGbc.anchor = GridBagConstraints.WEST;
        stockPanel.add(new JLabel("ISBN:"), stockGbc);
        stockGbc.gridx = 1; stockGbc.gridy = 0; stockGbc.fill = GridBagConstraints.HORIZONTAL; stockGbc.weightx = 1.0;
        stockIsbnField = new JTextField(15);
        stockPanel.add(stockIsbnField, stockGbc);

        // 数量
        stockGbc.gridx = 2; stockGbc.gridy = 0; stockGbc.fill = GridBagConstraints.NONE; stockGbc.weightx = 0;
        stockPanel.add(new JLabel("数量:"), stockGbc);
        stockGbc.gridx = 3; stockGbc.gridy = 0; stockGbc.fill = GridBagConstraints.HORIZONTAL; stockGbc.weightx = 1.0;
        stockQuantityField = new JTextField(10);
        stockPanel.add(stockQuantityField, stockGbc);

        // 库存操作按钮
        increaseStockButton = new JButton("增加库存");
        sellButton = new JButton("销售书籍");

        JPanel stockButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        stockButtonPanel.add(increaseStockButton);
        stockButtonPanel.add(sellButton);

        stockGbc.gridx = 0; stockGbc.gridy = 1; stockGbc.gridwidth = 4; stockGbc.fill = GridBagConstraints.HORIZONTAL;
        stockPanel.add(stockButtonPanel, stockGbc);
        
        topOperationsPanel.add(stockPanel);

        mainPanel.add(topOperationsPanel, BorderLayout.NORTH);

        // 中间表格面板
        String[] columnNames = {"ISBN", "书名", "作者", "价格", "库存"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }
        };
        bookTable = new JTable(tableModel);
        bookTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 只允许单行选择
        bookTable.setRowHeight(25); // 增加行高
        bookTable.setFont(new Font("宋体", Font.PLAIN, 14)); // 设置表格字体
        bookTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, 14)); // 设置表头字体
        JScrollPane scrollPane = new JScrollPane(bookTable);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 底部查询面板
        JPanel queryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        queryPanel.setBorder(BorderFactory.createTitledBorder("数据查询"));

        searchField = new JTextField(30);
        searchButton = new JButton("模糊查询 (书名/作者)");
        lowStockButton = new JButton("查询低库存 (低于10本)");

        queryPanel.add(new JLabel("查询关键词:"));
        queryPanel.add(searchField);
        queryPanel.add(searchButton);
        queryPanel.add(lowStockButton);
        mainPanel.add(queryPanel, BorderLayout.SOUTH);

        add(mainPanel);

        // 添加事件监听器
        addButton.addActionListener(e -> addBook());
        updateButton.addActionListener(e -> updateBook());
        deleteButton.addActionListener(e -> deleteBook());
        clearButton.addActionListener(e -> clearFields());
        increaseStockButton.addActionListener(e -> increaseStock());
        sellButton.addActionListener(e -> sellBook());
        searchButton.addActionListener(e -> searchBooks());
        lowStockButton.addActionListener(e -> showLowStockBooks());
        bookTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting() && bookTable.getSelectedRow() != -1) {
                displaySelectedBook();
            }
        });
    }

    private void loadBooks() {
        tableModel.setRowCount(0); // 清空现有数据
        List<Book> books = bookService.getAllBooks();
        for (Book book : books) {
            Vector<Object> row = new Vector<>();
            row.add(book.getIsbn());
            row.add(book.getTitle());
            row.add(book.getAuthor());
            row.add(book.getPrice());
            row.add(book.getStock());
            tableModel.addRow(row);
        }
    }

    private void clearFields() {
        isbnField.setText("");
        titleField.setText("");
        authorField.setText("");
        priceField.setText("");
        stockField.setText("");
        isbnField.setEnabled(true); // 允许编辑ISBN
    }

    private void displaySelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow != -1) {
            isbnField.setText(tableModel.getValueAt(selectedRow, 0).toString());
            titleField.setText(tableModel.getValueAt(selectedRow, 1).toString());
            authorField.setText(tableModel.getValueAt(selectedRow, 2).toString());
            priceField.setText(tableModel.getValueAt(selectedRow, 3).toString());
            stockField.setText(tableModel.getValueAt(selectedRow, 4).toString());
            isbnField.setEnabled(false); // 选中行后禁止编辑ISBN
        }
    }

    private void addBook() {
        try {
            String isbn = isbnField.getText().trim();
            String title = titleField.getText().trim();
            String author = authorField.getText().trim();
            double price = Double.parseDouble(priceField.getText().trim());
            int stock = Integer.parseInt(stockField.getText().trim());

            Book book = new Book(isbn, title, author, price, stock);
            if (bookService.addBook(book)) {
                JOptionPane.showMessageDialog(this, "书籍添加成功！");
                loadBooks();
                clearFields();
            } else {
                JOptionPane.showMessageDialog(this, "书籍添加失败！ISBN可能已存在或输入有误。");
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "价格和库存必须是有效数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "添加书籍时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateBook() {
        try {
            String isbn = isbnField.getText().trim();
            String title = titleField.getText().trim();
            String author = authorField.getText().trim();
            double price = Double.parseDouble(priceField.getText().trim());
            int stock = Integer.parseInt(stockField.getText().trim());

            Book book = new Book(isbn, title, author, price, stock);
            if (bookService.updateBook(book)) {
                JOptionPane.showMessageDialog(this, "书籍更新成功！");
                loadBooks();
                clearFields();
            } else {
                JOptionPane.showMessageDialog(this, "书籍更新失败！请确保ISBN存在。");
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "价格和库存必须是有效数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "更新书籍时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteBook() {
        String isbn = isbnField.getText().trim();
        if (isbn.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请选择要删除的书籍或输入ISBN！", "输入错误", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除ISBN为 " + isbn + " 的书籍吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            if (bookService.deleteBook(isbn)) {
                JOptionPane.showMessageDialog(this, "书籍删除成功！");
                loadBooks();
                clearFields();
            } else {
                JOptionPane.showMessageDialog(this, "书籍删除失败！请确保ISBN存在。");
            }
        }
    }

    private void increaseStock() {
        try {
            String isbn = stockIsbnField.getText().trim();
            int quantity = Integer.parseInt(stockQuantityField.getText().trim());

            if (bookService.increaseStock(isbn, quantity)) {
                JOptionPane.showMessageDialog(this, "库存增加成功！");
                loadBooks();
                stockIsbnField.setText("");
                stockQuantityField.setText("");
            } else {
                JOptionPane.showMessageDialog(this, "库存增加失败！请检查ISBN和数量。");
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "数量必须是有效数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void sellBook() {
        try {
            String isbn = stockIsbnField.getText().trim();
            int quantity = Integer.parseInt(stockQuantityField.getText().trim());

            if (bookService.sellBook(isbn, quantity)) {
                JOptionPane.showMessageDialog(this, "书籍销售成功！");
                loadBooks();
                stockIsbnField.setText("");
                stockQuantityField.setText("");
            } else {
                JOptionPane.showMessageDialog(this, "书籍销售失败！请检查ISBN、数量或库存是否充足。");
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "数量必须是有效数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void searchBooks() {
        String query = searchField.getText().trim();
        tableModel.setRowCount(0); // 清空现有数据
        List<Book> books = bookService.searchBooks(query);
        if (books.isEmpty() && !query.isEmpty()) {
            JOptionPane.showMessageDialog(this, "未找到匹配的书籍。", "查询结果", JOptionPane.INFORMATION_MESSAGE);
        }
        for (Book book : books) {
            Vector<Object> row = new Vector<>();
            row.add(book.getIsbn());
            row.add(book.getTitle());
            row.add(book.getAuthor());
            row.add(book.getPrice());
            row.add(book.getStock());
            tableModel.addRow(row);
        }
    }

    private void showLowStockBooks() {
        tableModel.setRowCount(0); // 清空现有数据
        List<Book> books = bookService.getLowStockBooks(10); // 低于10本
        if (books.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有库存低于10本的书籍。", "低库存查询", JOptionPane.INFORMATION_MESSAGE);
        }
        for (Book book : books) {
            Vector<Object> row = new Vector<>();
            row.add(book.getIsbn());
            row.add(book.getTitle());
            row.add(book.getAuthor());
            row.add(book.getPrice());
            row.add(book.getStock());
            tableModel.addRow(row);
        }
    }
} 